package demo.practice.leetcode_eveyday;

import demo.practice.TreeNode;

public class P671 {


    public static void main(String[] args) {
        P671 p671 = new P671();
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(2);
        root.right = new TreeNode(5);
        root.right.right = new TreeNode(7);
        root.right.left = new TreeNode(5);

        int secondMinimumValue = p671.findSecondMinimumValue(root);

    }

    public int findSecondMinimumValue(TreeNode root) {
        int res = -1;
        return (res = findSecondMinimumValue(root, root.val)) == root.val ? -1 : res;
    }

    public int findSecondMinimumValue(TreeNode node, int min) {
        if (node == null) {
            return min;
        }
        if (node.val > min) {
            return node.val;
        }
        //return Math.min(findSecondMinimumValue(node.left, min), findSecondMinimumValue(node.right, min));
        int l = findSecondMinimumValue(node.left, min);
        int r = findSecondMinimumValue(node.right, min);

        if (l == min || r == min) {
            return Math.max(l, r);
        } else {
            return Math.min(l, r);
        }
    }
}
